#rawEditsToFile.py
#
#Given namespace, offset year, raw edits, and cohort, write a file that can be read by R to create graphs
import sys
import collections
import os

def realMain():
	intNs = ["main", "talk", "user", "user talk", "project"]
	path1 = sys.argv[1]
	path2 = sys.argv[2]

	if os.path.isfile(path2+"rawedits.R"):
		os.remove(path2+"rawedits.R")
	global f3
	f3 = open(path2+"rawedits.R", "a+")



	for ns in intNs:
		main(path1, ns)

def main(thing1, thing2):
	
	maximum = 0
	minimum = 1000000000000000

	colorList = ["blue","red","orange","goldenrod4","black","green","coral","violet","skyblue","aquamarine4","blue"]
	years = ["2003","2004","2005","2006","2007","2008","2009","2010","2011"]
	yearList = []
	for x in range(0,len(years)):
		newList = "years"+str(x)
		newList = years[x:]
		yearList.append(newList)

	editcounts = thing1
	#totalaverages = sys.argv[2]
	namespace = thing2
	

	
	title = "Raw Edits for "
		

	filetitle = namespace

	tList = []
	yearDict = collections.defaultdict(list)
		
	#for x in range(2003,2013):
	#	for y in range(0,x-2003):
	#		yearDict[str(x)].append('0')
	
	f = open(editcounts, "r")
	
	for line in f:
		tokens = line.split("\t")
		if ((namespace in tokens[0] and "talk" not in namespace and "talk" not in tokens[0]) or ("talk" in namespace and namespace in tokens[0] and namespace <> "talk") or ("talk" == namespace and "talk" == tokens[0][:4])): 
			year = tokens[0][-5:-1]
			editcount = tokens[1].replace('\n','')
			if (int(tokens[0][-1]) + int(tokens[0][-3:-1])) <> 12:
				yearDict[year].append(editcount)
			if int(editcount) > maximum:
				maximum = int(editcount)
			if int(editcount) < minimum:
				minimum = int(editcount)

	
	namespaceTitle = namespace[0].upper()+namespace[1:]	
	namespace = namespace.replace(' ','')

	for key in sorted(yearDict.keys()):
	
		aList = yearDict[key]
		f3.write(namespace + key + " <- c(" + ",".join(aList) + ')\n')

	#print namespace + "total" + " <- c(" + ",".join(tList) + ')'
	
	num = 0
	for years in yearList:		
		f3.write("years" + str(num) + " <- c(" + ",".join(years) + ')\n')
		num += 1

	f3.write('jpeg("'+filetitle+'.jpeg", width=500, height=500, units = "px",res="72",quality="100")\n')
	f3.write('plot(years0, ' +namespace + "2003" + ', type="o", main="' + title + namespaceTitle + '",xlab="Year",ylab="Number of Edits",col="blue",ylim=c('+str(minimum)+','+str(maximum+maximum/20)+'))\n')
	y = 0
	for x in sorted(yearDict.keys()):			
		f3.write("lines(years"+str(y)+", " + namespace+str(x)+',type="o",col="'+colorList[y]+'")\n')
		y += 1
	f3.write('legend("topleft",legend=c("2003","2004","2005","2006","2007","2008","2009","2010","2011"),text.col=c("blue","red","orange","goldenrod4","black","green","coral","violet","skyblue","aquamarine4"), horiz = "TRUE", text.width = .425, bty = "n")\n')	
	f3.write("dev.off()\n")
	


realMain()
